from src.image_handler.image_processor import ImageProcessor
from src.image_handler.obs_uploader import OBSUploader
import re

class ImageHandler:
    """图片处理器封装类"""
    
    def __init__(self, config: dict):
        self.config = config
        self.processor = ImageProcessor(config)
        self.uploader = OBSUploader(config)
        
    def process_images(self, images: list, source_name: str) -> list:
        """处理图片列表并上传到OBS
        
        Args:
            images: 从文档中提取的图片列表
            source_name: 文档英文名称，用作图片存储路径前缀
            
        Returns:
            list: 处理后的图片URL列表，每个元素包含url、page和index信息
        """
        image_urls = []
        
        # 创建新的配置，添加 manual_name
        upload_config = dict(self.config)
        upload_config['manual_name'] = source_name
        
        # 使用新配置创建上传器
        uploader = OBSUploader(upload_config)
        
        for image in images:
            # 处理图片（压缩、格式转换等）
            processed_image = self.processor.process(image)
            
            if processed_image:
                # 上传到OBS并获取URL
                try:
                    url = uploader.upload(processed_image)
                    if url:
                        image_urls.append({
                            'url': url,
                            'page': image['page'],
                            'index': image['index']
                        })
                except Exception as e:
                    print(f"上传图片失败: {str(e)}")
                    continue
                    
        return image_urls
    
    def replace_image_references(self, content: str, image_urls: list) -> str:
        """替换文本中的图片引用为OBS URL
        
        Args:
            content: 文档文本内容
            image_urls: 图片URL列表，每个元素包含url、page和index信息
            
        Returns:
            str: 替换后的文本内容
        """
        if not image_urls:
            return content
            
        # 按页码和索引排序图片URL
        image_map = {}
        for img in image_urls:
            page_key = f"page_{img['page']}"
            if page_key not in image_map:
                image_map[page_key] = {}
            image_map[page_key][img['index']] = img['url']
            
        # 替换图片引用
        def replace_image(match):
            try:
                page = int(match.group(1))
                index = int(match.group(2))
                page_key = f"page_{page}"
                if page_key in image_map and index in image_map[page_key]:
                    return f"![图片]({image_map[page_key][index]})"
                return match.group(0)  # 如果找不到对应的URL，保持原样
            except:
                return match.group(0)
                
        # 匹配形如 ![](@page_1_image_2) 的图片引用
        pattern = r"!\[\]\(@page_(\d+)_image_(\d+)\)"
        replaced_content = re.sub(pattern, replace_image, content)
        
        return replaced_content 